package com.whq.knowverywell.business.http;

import java.net.URLDecoder;
import java.net.URLEncoder;

import org.json.JSONObject;

import android.content.Context;

import com.whq.knowverywell.business.db.TblConfHandler;
import com.whq.knowverywell.business.db.TblUserHandler;
import com.whq.knowverywell.business.model.User;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.NetworkUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.httpclient.HttpClientUtil;
import com.whq.knowverywell.util.httpclient.HttpResult;


/**
 * 登录工具类
 * @author wanghuaiqiang
 *
 */
public class LoginUtil {
	private static final String TAG = "LoginUtil";
	
	/**
	 * 登录
	 * @param context
	 * @param groupCode
	 * @param userName
	 * @param password
	 * @param rememberMe
	 * @return
	 */
	public static boolean login(Context context, String groupCode, String userName, String password, boolean rememberMe) {
		if (context == null) {
			return false;
		}
		if (!NetworkUtil.isNetworkAvailable(context)) {
			return false;
		}
		
		// 获取guid
		String path = CfgConstant.SERVER_CONTEXT + "/login/getGuid.php";
		StringBuilder sb = new StringBuilder();
		sb.append("version=" + CfgConstant.SERVER_API_VERSION);
		sb.append("&source=" + CfgConstant.SERVER_API_SOURCE);
		
		String req = sb.toString();
		HttpResult httpResult = HttpClientUtil.callServer(context, CfgConstant.SERVER_HOST, false, path, req, "UTF-8");
		if ( (httpResult == null) 
				|| (!httpResult.checkCode()) 
				) {
			return false;
		}
		
		String responseStr = httpResult.getResp();
		if (StringUtil.isBlank(responseStr)) {
			return false;
		}
		
		String guid = "";
		String publicKey = "";
		try {
			JSONObject recordJson = new JSONObject(responseStr);
			int resultCode = recordJson.optInt("resultCode", -1);
			if (resultCode != 0) {
				return false;
			}
			if (recordJson.isNull("data")) {
				return false;
			}
			JSONObject dataJson = recordJson.optJSONObject("data");
			if (dataJson == null) {
				return false;
			}
			guid = dataJson.optString("guid", "");
			publicKey = dataJson.optString("publicKey", "");
			LogUtil.i(TAG, "publicKey 1: " + publicKey);
			publicKey = publicKey.replace("-----BEGIN+PUBLIC+KEY-----%0A", "");
			publicKey = publicKey.replace("-----END+PUBLIC+KEY-----%0A", "");
			
			publicKey = URLDecoder.decode(publicKey, "UTF-8");
			if ( StringUtil.isBlank(guid) || StringUtil.isBlank(publicKey) ){
				return false;
			}
			
		} catch (Exception e) {
			LogUtil.e(TAG, "解析json串出错：", e);
			return false;
		}
		
		LogUtil.i(TAG, "guid: " + guid);
		LogUtil.i(TAG, "publicKey 2: " + publicKey);
		
		// 登录
		JSONObject userDataJson = new JSONObject();
		try {
			userDataJson.put("groupCode", groupCode);
			userDataJson.put("userName", userName);
			userDataJson.put("password", password);
			userDataJson.put("guid", guid);
		} catch (Exception e) {
			LogUtil.e(TAG, "拼接json串出错：", e);
			return false;
		}
		
		LogUtil.i(TAG, "userDataJson: " + userDataJson.toString());
		
//		byte[] origData = userDataJson.toString().getBytes();  
//		byte[] encodedData = null;
//		try {
//			encodedData = RSACoder.encryptByPublicKey(origData, publicKey);
//		} catch (Exception e) {
//			LogUtil.e(TAG, "rsa公钥加密出错：", e);
//			return false;
//		}
        
        String urlencodeUserData = "";
        try {
        	urlencodeUserData = URLEncoder.encode(userDataJson.toString(), "UTF-8") ;
        } catch (Exception e) {
        	LogUtil.e(TAG, "解析json串出错：", e);
			return false;
        }
		
		path = CfgConstant.SERVER_CONTEXT + "/login/login.php";
		sb = new StringBuilder();
		sb.append("guid=" + guid);
		sb.append("&userData=" + urlencodeUserData);
		sb.append("&version=" + CfgConstant.SERVER_API_VERSION);
		sb.append("&source=" + CfgConstant.SERVER_API_SOURCE);
		req = sb.toString();
		httpResult = HttpClientUtil.callServer(context, CfgConstant.SERVER_HOST, false, path, req, "UTF-8");
		
		// 根据结果获取token
		if ( (httpResult == null) 
				|| (!httpResult.checkCode()) 
				) {
			return false;
		}
		
		responseStr = httpResult.getResp();
		if (StringUtil.isBlank(responseStr)) {
			return false;
		}
		
		try {
			JSONObject recordJson = new JSONObject(responseStr);
			int resultCode = recordJson.optInt("resultCode", -1);
			if (resultCode != 0) {
				return false;
			}
			if (recordJson.isNull("data")) {
				return false;
			}
			JSONObject dataJson = recordJson.optJSONObject("data");
			if (dataJson == null) {
				return false;
			}
			String token = dataJson.optString("token", "");
			LogUtil.i(TAG, "登录成功，token：" + token);
			
			// 记录登录信息
			TblConfHandler tblConfHandler = new TblConfHandler(context);
			tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_GROUP_CODE, groupCode);
			tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_USER_NAME, userName);
			tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_TOKEN, token);
			
			if (rememberMe) {
				TblUserHandler tblUserHandler = new TblUserHandler(context);
				User oneUser = new User();
				oneUser.setGroupCode(groupCode);
				oneUser.setPassword(password);
				oneUser.setUserName(userName);
				tblUserHandler.addOrUpdUser(oneUser);
			}
			
			return true;
		} catch (Exception e) {
			LogUtil.e(TAG, "解析json串出错：", e);
			return false;
		}
    }
	
	/**
	 * 是否已经登录
	 * @param context
	 * @return
	 */
	public static boolean chkLogin(Context context) {
		if (context == null) {
			return false;
		}
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		String loginToken = tblConfHandler.getOneConf(TblConfHandler.KEY_LOGIN_TOKEN);
		if (StringUtil.isNotBlank(loginToken)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取登录token
	 * @param context
	 * @return
	 */
	public static String getLoginToken(Context context) {
		if (context == null) {
			return "";
		}
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		return tblConfHandler.getOneConf(TblConfHandler.KEY_LOGIN_TOKEN);
	}
	
	/**
	 * 获取登录用户公司编号
	 * @param context
	 * @return
	 */
	public static String getLoginGroupCode(Context context) {
		if (context == null) {
			return "";
		}
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		return tblConfHandler.getOneConf(TblConfHandler.KEY_LOGIN_GROUP_CODE);
	}
	
	/**
	 * 获取登录用户的用户名
	 * @param context
	 * @return
	 */
	public static String getLoginUserName(Context context) {
		if (context == null) {
			return "";
		}
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		return tblConfHandler.getOneConf(TblConfHandler.KEY_LOGIN_USER_NAME);
	}
	
	/**
	 * 清空登录信息
	 * @param context
	 */
	public static void clearLogin(Context context) {
		if (context == null) {
			return ;
		}
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_GROUP_CODE, "");
		tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_USER_NAME, 	"");
		tblConfHandler.saveOneConf(TblConfHandler.KEY_LOGIN_TOKEN, 		"");
	}
}
